﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using SalePartial.Utility;
using System.Collections;
using Telerik.Web.UI;
using System.Data;
using XunPan.Web.Globals;
using System.Collections.Specialized;
using SalePartial.BLL;
using SalePartial.Model;
using System.Data.SqlClient;

public partial class Trade_Resource_trade_retrieval : System.Web.UI.Page
{
   protected void Page_Load(object sender, System.EventArgs e)
{
	if (!IsPostBack) {

        ////■■■■■テストため■■■■
        //UserBLL.StoreUserInfoToSession("j@j10.com");
        LoginUserType type = RoleControlManager.checkUserAuthority(User.Identity.Name);
        if (type == LoginUserType.FREE_SUPPLY
            || type == LoginUserType.CERT_SUPPLY || type == LoginUserType.CERT_SUP_PUR
            || type == LoginUserType.FREE_SUP_PUR)
        {

			LoadProvinces();
			rcSharedSubmitDate.RangeMaxDate = System.DateTime.Now;

            if (Session["s_companyID_guid"] != null)
            {
                sdsEventsList.SelectParameters["VendorCompanyID"].DefaultValue = Session["s_companyID_guid"].ToString();
                sdsEventsList.FilterParameters["Filter1"].DefaultValue = "";
            }
			//'此处本来动态加载省市的树状目录，但由于集成检索条件的编辑功能，所以改为一次全部加载
			//'LoadRootNodes(rtvLocation, TreeNodeExpandMode.ServerSide)
			//LoadRootNodes(rtvLocation, TreeNodeExpandMode.ServerSideCallBack)
			LoadAllLocationNodes(rtvLocation);

            LoadFilterExpressions();

            if (Session["InquiryFilterID"] != null)
            {
                for(int i= 0;i<rcbFilters.Items.Count;i++)
                {
                    if (rcbFilters.Items[i].Value.Split(Environment.NewLine.ToCharArray())[0] == Session["InquiryFilterID"].ToString())
                    {
                        rcbFilters.SelectedIndex = i;
                        break;
                    }
                }

                btnEditFilter_Click(null, null);
            }

		} else {
            Response.Redirect(GlobalSetting.UrlHomePage, true);
		}
	}


}


protected void Page_PreRender(object sender, System.EventArgs e)
{
	//在测试模式中
	//由于是在页面内认证用户
	//第一次Load页面将无法读取用户cookie
	//因此无法加载对应的profile属性

    //LoadFilterExpressions();
}

//**************************************************************************************************************************8
//此代码将加载用户自定义的检索条件至下拉菜单

//**************************************************************************************************************************8


private void LoadFilterExpressions()
{


    //if (!Context.Profile.IsAnonymous) {
    //    StringDictionary temp = (StringDictionary)Context.Profile.GetPropertyValue("InquiryEventFilter");
    //    if (temp != null && temp.Count > 0) {
    //        rcbFilters.Items.Clear();
    //        //读取对应属性的配置
    //        //Load Property
    //        foreach (DictionaryEntry de in temp) {
    //            rcbFilters.Items.Add(new RadComboBoxItem(de.Key.ToString(), de.Value.ToString()));
    //        }
    //    }
    //}

    XPInquiryFilter xpInquFilter = new XPInquiryFilter();
    SqlDataReader reader = xpInquFilter.SelectReaderByCompanyID(new Guid(sdsEventsList.SelectParameters["VendorCompanyID"].DefaultValue));
    try
    {
        rcbFilters.Items.Clear();
        while (reader.Read())
        {
            XPInquiryFilterInfo info = new XPInquiryFilterInfo(reader);
            rcbFilters.Items.Add(new RadComboBoxItem(info.FilterName, info.InquiryFilterID+Environment.NewLine+info.FilterExpression));
        }
        if (!reader.IsClosed)
        {
            reader.Close();
        }
    }
    catch (Exception e)
    {

    }

}


//**************************************************************************************************************************8
//该部分代码将加载省市联动下拉菜单
//**************************************************************************************************************************8



private void LoadProvinces()
{
	rcbProvince.DataTextField = "ProvinceName";
	rcbProvince.DataValueField = "ID";
	rcbProvince.DataSource = xdsProvinces;

	rcbProvince.DataBind();
	//insert the first item
	rcbProvince.Items.Insert(0, new RadComboBoxItem("- 所有省份 -"));
}

private void LoadCites(string provinceID)
{
	xdsCities.XPath = "/Cities/City[@PID='" + provinceID + "']";
	rcbCity.DataTextField = "CityName";
	rcbCity.DataValueField = "ID";
	rcbCity.DataSource = xdsCities;
	rcbCity.DataBind();
	rcbCity.Items.Insert(0, new RadComboBoxItem("- 所有城市 -"));
}

protected void rcbProvince_SelectedIndexChanged(object o, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
{
	if (rcbProvince.SelectedIndex > 0) {
		LoadCites(e.Value);
	} else {
		rcbCity.Text = "";
        //rcbCity.Items.Clear();

	}
}

protected void rcbCity_SelectedIndexChanged(object o, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
{

}
//Protected Sub rcbCity_ItemsRequested(ByVal o As Object, ByVal e As Telerik.Web.UI.RadComboBoxItemsRequestedEventArgs) Handles rcbCity.ItemsRequested
//    LoadCites(e.Text)
//End Sub

//Protected Sub rcbProvince_ItemsRequested(ByVal o As Object, ByVal e As Telerik.Web.UI.RadComboBoxItemsRequestedEventArgs) Handles rcbProvince.ItemsRequested
//    LoadProvinces()
//End Sub

//Protected Sub rcbCountry_ItemsRequested(ByVal o As Object, ByVal e As Telerik.Web.UI.RadComboBoxItemsRequestedEventArgs) Handles rcbCountry.ItemsRequested

//End Sub





//**************************************************************************************************************************8
//此部分代码将动态加载省市树状目录的加载
//但由于集成了编辑功能，需要树状目录一次加载完毕，因此该部分代码没有启用
//**************************************************************************************************************************8


private static void LoadRootNodes(RadTreeView treeView, TreeNodeExpandMode expandMode)
{
	DataSet data = new DataSet();
	data.ReadXml(HttpContext.Current.Server.MapPath("~/App_Data/XML/China_Provinces.xml"));


	foreach (DataRow row in data.Tables[0].Rows) {
		RadTreeNode node = new RadTreeNode();
		node.Text = row["ProvinceName"].ToString();
		node.Value = row["ID"].ToString();
		node.ExpandMode = expandMode;
		treeView.Nodes.Add(node);
	}

}

private static void LoadAllLocationNodes(RadTreeView treeView)
{
	DataSet data = new DataSet();
	data.ReadXml(HttpContext.Current.Server.MapPath("~/App_Data/XML/China_Provinces.xml"));


	foreach (DataRow row in data.Tables[0].Rows) {
		RadTreeNode provincenode = new RadTreeNode();
		provincenode.Text = row["ProvinceName"].ToString();
		provincenode.Value = row["ID"].ToString();


		DataTable dt = GetCitiesData(provincenode.Value);

		foreach (DataRow dr in dt.Rows) {
			RadTreeNode citynode = new RadTreeNode();
			citynode.Text = dr["CityName"].ToString();
			citynode.Value = dr["ID"].ToString();
			provincenode.Nodes.Add(citynode);
		}

		treeView.Nodes.Add(provincenode);
	}


}

private static DataTable GetCitiesData(string pid)
{
	DataSet data = new DataSet();
	data.ReadXml(HttpContext.Current.Server.MapPath("~/App_Data/XML/China_Cities.xml"));

	DataView dv = new DataView(data.Tables[0]);
	//dv.Sort = "CityName ASC"
	dv.RowFilter = "[PID] = '" + pid + "'";
	return dv.ToTable();

}
private static void PopulateNodeOnDemand(RadTreeNodeEventArgs e, TreeNodeExpandMode expandMode)
{
	DataTable data = GetCitiesData(e.Node.Value);

	foreach (DataRow row in data.Rows) {
		RadTreeNode node = new RadTreeNode();
		node.Text = row["CityName"].ToString();
		node.Value = row["ID"].ToString();
		e.Node.Nodes.Add(node);
	}

	e.Node.Expanded = true;
}

protected void rtvLocation_NodeExpand(object sender, Telerik.Web.UI.RadTreeNodeEventArgs e)
{
	PopulateNodeOnDemand(e, TreeNodeExpandMode.ServerSideCallBack);
	//PopulateNodeOnDemand(e, TreeNodeExpandMode.ServerSide)

}



//**************************************************************************************************************************8
//下面代码断包括所有对filter的处理
//
//**************************************************************************************************************************8


protected void btnNewFilter_Click(object sender, System.EventArgs e)
{
	//此处将设置用户存储检索条件的最大数目

	if (rcbFilters.Items.Count >= GlobalSetting.MaxSavedFilterQuantity) {
		lblErrorMessage.Text = "无法新建检索条件 - 保存的检索条件数量已超过最大值, 请删除一条或多条检索条件";
		lblErrorMessage.Visible = true;
		return;
	} else {
		lblErrorMessage.Visible = false;

	}

	rdzFilterBuilder1.Visible = rdockFilterMenu.Visible;
	rdzFilterBuilder2.Visible = rdockFilterMenu.Visible;
	rdockFilterMenu.Visible = !rdockFilterMenu.Visible;

}


protected void btnEditFilter_Click(object sender, System.EventArgs e)
{

	if (rcbFilters.SelectedIndex >= 0) {

        //if (!Context.Profile.IsAnonymous) {
        //    StringDictionary filterFromProfile = (StringDictionary)Context.Profile.GetPropertyValue("InquiryEventFilter");

        //    if (filterFromProfile.ContainsKey(rcbFilters.SelectedItem.Text)) {
        //        rtbFilterName.Text = rcbFilters.SelectedItem.Text;
        //        rtbFilterName.Enabled = false;

        //        string filterValue = (string)filterFromProfile[rcbFilters.SelectedItem.Text];
        //        filterValue = GlobalUtility.DeserialzedFromString(filterValue);
        //        ParseFilterExpression(filterValue);
        //    } else {
        //        return;

        //    }

        //} else {
        //    return;

        //}
        string[] value =  rcbFilters.SelectedValue.Split(Environment.NewLine.ToCharArray());
        if(value.Length == 3)
        {
            rtbFilterName.Text = rcbFilters.SelectedItem.Text;
            rtbFilterName.Enabled = false;

            string filterValue = value[2];
            filterValue = GlobalUtility.DeserialzedFromString(filterValue);
            ParseFilterExpression(filterValue);
        }
        

	} else {
		return;

	}

	rdzFilterBuilder1.Visible = rdockFilterMenu.Visible;
	rdzFilterBuilder2.Visible = rdockFilterMenu.Visible;
	rdockFilterMenu.Visible = !rdockFilterMenu.Visible;

}

protected void btnDeleteFilter_Click(object sender, System.EventArgs e)
{

	if (rcbFilters.SelectedIndex >= 0) {

        //if (!Context.Profile.IsAnonymous) {
        //    StringDictionary temp = (StringDictionary)Context.Profile.GetPropertyValue("InquiryEventFilter");

        //    if (temp.ContainsKey(rcbFilters.SelectedItem.Text)) {
        //        temp.Remove(rcbFilters.SelectedItem.Text);
        //    }
        //    Context.Profile.SetPropertyValue("InquiryEventFilter", temp);
        //    Context.Profile.Save();
        //    LoadFilterExpressions();

        //}

        string[] value = rcbFilters.SelectedValue.Split(Environment.NewLine.ToCharArray());
        if (value.Length == 3)
        {
            try
            {
                string inquiryFilterID = value[0];
                XPInquiryFilter xpInquFilter = new XPInquiryFilter();
                xpInquFilter.Delete(new Guid(inquiryFilterID));
            }
            catch (Exception )
            {
            }
            LoadFilterExpressions();
        }

	}
}

protected void btnApplyFilter_Click(object sender, System.EventArgs e)
{
    if (rcbFilters.SelectedIndex >= 0)
    {
        string[] value = rcbFilters.SelectedValue.Split(Environment.NewLine.ToCharArray());
        if (value.Length == 3)
        {
            sdsEventsList.FilterParameters["Filter1"].DefaultValue = GlobalUtility.DeserialzedFromString(value[2]);
        }
    }

	if (rcbProvince.SelectedIndex > 0) {

        if (string.IsNullOrEmpty(sdsEventsList.FilterParameters["Filter1"].DefaultValue))
        {
            sdsEventsList.FilterParameters["Filter1"].DefaultValue = "[Province] = '" + rcbProvince.SelectedItem.Text + "'";
		} else {
            sdsEventsList.FilterParameters["Filter1"].DefaultValue += "AND [Province] = '" + rcbProvince.SelectedItem.Text + "'";
		}

	}

	if (rcbCity.SelectedIndex > 0) {
        if (string.IsNullOrEmpty(sdsEventsList.FilterParameters["Filter1"].DefaultValue))
        {
            sdsEventsList.FilterParameters["Filter1"].DefaultValue = "[City] = '" + rcbCity.SelectedItem.Text + "'";
		} else {
            sdsEventsList.FilterParameters["Filter1"].DefaultValue += "AND [City] = '" + rcbCity.SelectedItem.Text + "'";
		}
	}
	radGridMainlist.DataBind();
}

protected void btnRemoveFilter_Click(object sender, System.EventArgs e)
{
    sdsEventsList.FilterParameters["Filter1"].DefaultValue = "";
	rcbProvince.Text = "";
	rcbProvince.ClearSelection();
	rcbCity.Text = "";
	rcbCity.Items.Clear();

    rcbFilters.SelectedIndex = -1;

	radGridMainlist.DataBind();

}

protected void btnSaveFilter_Click(object sender, System.EventArgs e)
{
    //if (!Context.Profile.IsAnonymous) {
		string filterName = rtbFilterName.Text;
		string filterExpression = BuildFilterExpression();
		filterExpression = GlobalUtility.SerializedAsString(filterExpression);

        XPInquiryFilter xpInquFilter = new XPInquiryFilter();
        if (rtbFilterName.Enabled)
        {
            XPInquiryFilterInfo xpInquFilterInfo = new XPInquiryFilterInfo();
            xpInquFilterInfo.CompanyID = new Guid(sdsEventsList.SelectParameters["VendorCompanyID"].DefaultValue);
            xpInquFilterInfo.FilterName = filterName;
            xpInquFilterInfo.FilterExpression = filterExpression;
            xpInquFilter.Insert(xpInquFilterInfo);
        }
        else
        {
            string[] value = rcbFilters.SelectedValue.Split(Environment.NewLine.ToCharArray());
            if (value.Length == 3)
            {

                XPInquiryFilterInfo xpInquFilterInfo  = xpInquFilter.SelectInfoByFilterID(new Guid(value[0]));
                if (xpInquFilterInfo != null)
                {
                    xpInquFilterInfo.FilterName = filterName;
                    xpInquFilterInfo.FilterExpression = filterExpression;
                    xpInquFilter.Update(xpInquFilterInfo);
                }
            }

        }
        LoadFilterExpressions();

        //StringDictionary filterFromProfile = (StringDictionary)Context.Profile.GetPropertyValue("InquiryEventFilter");
        //if (filterFromProfile == null || filterFromProfile.Count == 0) {
        //    //该用户没有对应属性的配置文件
        //    //Set Property
        //    filterFromProfile = new StringDictionary();
        //}
        ////判断是否为编辑模式
        //if (rtbFilterName.Enabled) {
        //    //此处将设置用户存储检索条件的最大数目
        //    if (filterFromProfile.Count >= GlobalSetting.MaxSavedFilterQuantity) {
        //        return;
        //    }

        //    if (string.IsNullOrEmpty(filterName) || filterFromProfile.ContainsKey(filterName)) {
        //        return;
        //    }

        //    filterFromProfile.Add(filterName, filterExpression);

        //} else {
        //    filterFromProfile[filterName] = filterExpression;
        //}
    //    Context.Profile.SetPropertyValue("InquiryEventFilter", filterFromProfile);
    //    Context.Profile.Save();

    //    LoadFilterExpressions();
    //}



	ResetFilterInputControls();

	rdzFilterBuilder1.Visible = rdockFilterMenu.Visible;
	rdzFilterBuilder2.Visible = rdockFilterMenu.Visible;
	rdockFilterMenu.Visible = !rdockFilterMenu.Visible;
}

private string BuildFilterExpression()
{
	StringCollection fe = new StringCollection();

	if (rntbMaxQuantity.Value != null) {
		fe.Add("[MaxQuantity] <=" + rntbMaxQuantity.Value.ToString());

	}

	if (rntbMinQuantity.Value != null) {
		fe.Add("[MaxQuantity] >=" + rntbMinQuantity.Value.ToString());

	}

	if (rdpFromSubmit.SelectedDate != null) {
		fe.Add("[AssignDate] >= '" + rdpFromSubmit.SelectedDate.Value.ToString("d") + "'");
	}

	if (rdpToSubmit.SelectedDate != null) {
		fe.Add("[AssignDate] <= '" + rdpToSubmit.SelectedDate.Value.ToString("d") + "'");
	}


	if (rtvLocation.CheckedNodes.Count > 0) {
		string provinceFilter = "";
		string cityFilter = "";

		foreach (RadTreeNode rtNode in rtvLocation.CheckedNodes) {
			switch (rtNode.Level) {
				case 0:
					provinceFilter = provinceFilter + rtNode.Text + "','";
					break;
				case 1:
					cityFilter = cityFilter + rtNode.Text + "','";
					break;
				case 2:

					break;
				default:

					break;
			}
		}

		if (provinceFilter.EndsWith(",'")) {
            provinceFilter = "[Province] IN ('" + provinceFilter.Remove(provinceFilter.LastIndexOf(",'")) + ")";
			//fe.Add(provinceFilter)
            //provinceFilter = "([Province] IN ('" + provinceFilter.Remove(provinceFilter.LastIndexOf(",'")) + "))";
		}

		if (cityFilter.EndsWith(",'")) {
			cityFilter = "[City] IN ('" + cityFilter.Remove(cityFilter.LastIndexOf(",'")) + ")";
			//fe.Add(cityFilter)
            //cityFilter = "([City] IN ('" + cityFilter.Remove(cityFilter.LastIndexOf(",'")) + "))";
		}
		fe.Add(provinceFilter + " OR " + cityFilter);

	}

	//build warecube / process fields
	if (rtvCategoryTree.CheckedNodes.Count > 0) {
		string warecubeFilter = "";
		foreach (RadTreeNode rtNode in rtvCategoryTree.CheckedNodes) {
			if (!rtvCategoryTree.CheckedNodes.Contains(rtNode.ParentNode)) {
                warecubeFilter += string.Format("([Category] LIKE '%{0}%') OR ", rtNode.Value);
			}
		}
		warecubeFilter = warecubeFilter.Remove(warecubeFilter.LastIndexOf(" OR "));

		fe.Add(warecubeFilter);
	}
	if (rtvProcessTree.CheckedNodes.Count > 0) {
		string processFilter = "";
		foreach (RadTreeNode rtNode in rtvProcessTree.CheckedNodes) {
			if (!rtvProcessTree.CheckedNodes.Contains(rtNode.ParentNode)) {
                processFilter += string.Format("([Category] LIKE '%{0}%') OR ", rtNode.Value);
			}
		}
		processFilter = processFilter.Remove(processFilter.LastIndexOf(" OR "));

		fe.Add(processFilter);
	}



	if (fe.Count > 0) {
		string fullExpression = "(";
		for (int i = 0; i <= fe.Count - 1; i++) {
			fullExpression = fullExpression + fe[i] + ") AND (";
		}
		fullExpression = fullExpression.Remove(fullExpression.LastIndexOf(" AND ("));
		return fullExpression;

	} else {
		return "";
	}

}

private void ParseFilterExpression(string filter)
{
	filter = filter.Trim();

	if (filter.StartsWith("(")) {
		filter = filter.Substring(1);
	}
	if (filter.EndsWith(")")) {
		filter = filter.Remove(filter.Length - 1);
	}

	string[] separator = { ") AND (" };

	string[] sa = filter.Split(separator, StringSplitOptions.RemoveEmptyEntries);

	if (sa.Length > 0) {
		string r = "'";


		for (int i = 0; i <= sa.Length - 1; i++) {
			sa[i] = sa[i].Trim();
			if (sa[i].StartsWith("[MaxQuantity] <=")) {
				rntbMaxQuantity.Value = Convert.ToDouble(sa[i].Replace("[MaxQuantity] <=", ""));
			}
			if (sa[i].StartsWith("[MaxQuantity] >=")) {
				rntbMinQuantity.Value = Convert.ToDouble(sa[i].Replace("[MaxQuantity] >=", ""));
			}



			if (sa[i].StartsWith("[AssignDate] >= '")) {
				rdpFromSubmit.SelectedDate = Convert.ToDateTime(sa[i].Replace("[AssignDate] >= ", "").Trim(r.ToCharArray()));
			}


			if (sa[i].StartsWith("[AssignDate] <= '")) {
				rdpToSubmit.SelectedDate = Convert.ToDateTime(sa[i].Replace("[AssignDate] <= ", "").Trim(r.ToCharArray()));
			}

			if (sa[i].StartsWith("[Province] IN (")) {
				string temp = sa[i].Replace("[Province] IN ('", "");
				temp = temp.Remove(temp.Length - 2);
				temp = temp.Replace("','", "|");
				string[] provinces = temp.Split('|');

				for (int k = 0; k <= provinces.Length - 1; k++) {
					RadTreeNode rtNode = rtvLocation.FindNodeByText(provinces[k]);
                    if (rtNode != null)
                    {
                        rtNode.Checked = true;
                    }
				}

			}

			if (sa[i].StartsWith("[City] IN (")) {
				string temp = sa[i].Replace("[City] IN ('", "");
				temp = temp.Remove(temp.Length - 2);
				temp = temp.Replace("','", "|");
                string[] cities = temp.Split('|');

				for (int k = 0; k <= cities.Length - 1; k++) {
					RadTreeNode rtNode = rtvLocation.FindNodeByText(cities[k]);
					rtNode.Checked = true;
				}

			}

			if (sa[i].StartsWith("([Product] LIKE")) {
				rtvCategoryTree.DataBind();

				string temp = sa[i].Replace("%')", "");
				temp = temp.Replace("([Product] LIKE '%", "");
				temp = temp.Replace(" OR ", "|");
				string[] warecubes = temp.Split('|');

				for (int k = 0; k <= warecubes.Length - 1; k++) {
					RadTreeNode rtNode = rtvCategoryTree.FindNodeByValue(warecubes[k]);
					rtNode.Checked = true;
				}
			}

			if (sa[i].StartsWith("([Technology] LIKE")) {
				rtvProcessTree.DataBind();

				string temp = sa[i].Replace("%')", "");
				temp = temp.Replace("([Technology] LIKE '%", "");
				temp = temp.Replace(" OR ", "|");
                string[] process = temp.Split('|');

				for (int k = 0; k <= process.Length - 1; k++) {
					RadTreeNode rtNode = rtvProcessTree.FindNodeByValue(process[k]);
					rtNode.Checked = true;

				}

			}

		}

	}



}

protected void btnClearFilter_Click(object sender, System.EventArgs e)
{
	bool isEditMode = !rtbFilterName.Enabled;
	string p = rtbFilterName.Text;
	ResetFilterInputControls();
	if (isEditMode) {
		rtbFilterName.Enabled = isEditMode;
		rtbFilterName.Text = p;
	}

    sdsEventsList.FilterParameters["Filter1"].DefaultValue = "";
    rtvLocation.UncheckAllNodes();
    rtvLocation.UnselectAllNodes();
    rtvProcessTree.UncheckAllNodes();
    rtvProcessTree.UnselectAllNodes();
    rtvCategoryTree.UncheckAllNodes();
    rtvCategoryTree.UnselectAllNodes();
	radGridMainlist.DataBind();

}

protected void btnExeFilter_Click(object sender, System.EventArgs e)
{
	

    sdsEventsList.FilterParameters["Filter1"].DefaultValue = BuildFilterExpression();

	radGridMainlist.DataBind();



}

protected void btnReturn_Click(object sender, System.EventArgs e)
{
	ResetFilterInputControls();

	rdzFilterBuilder1.Visible = rdockFilterMenu.Visible;
	rdzFilterBuilder2.Visible = rdockFilterMenu.Visible;
	rdockFilterMenu.Visible = !rdockFilterMenu.Visible;
}

private void ResetFilterInputControls()
{
	rtbFilterName.Enabled = true;
	rtbFilterName.Text = "";
	rdpFromSubmit.Clear();
	rdpToSubmit.Clear();
	rntbMaxQuantity.Text = "";
	rntbMinQuantity.Text = "";
	rtvLocation.UncheckAllNodes();
	rtvLocation.UnselectAllNodes();
}


protected void rtvCategoryTree_DataBound(object sender, System.EventArgs e)
{
}

protected void radGridMainlist_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
{
	if (e.CommandName.ToLower() == "createevents") {
		for (int i = 0; i <= radGridMainlist.SelectedIndexes.Count - 1; i++) {
			int index = Convert.ToInt32(radGridMainlist.SelectedIndexes[i]);

            string inquiryid = radGridMainlist.MasterTableView.DataKeyValues[index]["InquiryID"].ToString();

			string vendorid = Session["s_companyID_guid"].ToString();


            {
                XPInquiryEvent xpinqEv = new XPInquiryEvent();
                DataSet ds = xpinqEv.SelectDynamic(string.Format("[VendorCompanyID] = '{0}' AND [InquiryID] = '{1}'", vendorid, inquiryid), "");

                if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    //ignore the selection
                    DataTable dt = ds.Tables[0];
                    int count = dt.Rows.Count;
                    Trace.Warn(count.ToString());

                }
                else
                {
                    XPInquiryEventInfo xpeventInfo = new XPInquiryEventInfo();
                    try
                    {
                        var _with1 = xpeventInfo;
                        _with1.BuyerCompanyID = new Guid(radGridMainlist.MasterTableView.DataKeyValues[index]["CompanyID"].ToString());
                        _with1.VendorCompanyID = new Guid(vendorid);
                        _with1.InquiryID = new Guid(inquiryid);
                        _with1.QuoteID = Guid.Empty;

                        xpinqEv.Insert(xpeventInfo);


                    }
                    catch (Exception ex)
                    {
                    }

                }
            }


		}
        radGridMainlist.Rebind();
		e.Canceled = true;

	}
}

}